﻿using System.Collections.Generic;
using System.Linq;
using System.Modules.ExceptionHanlding;
using System.Xml;
using Microsoft.SharePoint;

namespace System.Modules.SharePoint.Extensions
{
    /// <summary>
    /// SP Field Multi Choice Extensions
    /// </summary>
    public static class SPFieldMultiChoiceExtensions
    {
        #region Populate
        /// <summary>
        /// Use this method to populate SP Choice field from a SP List
        /// </summary>
        /// <param name="field"></param>
        /// <param name="list"></param>
        public static void Populate(this SPFieldMultiChoice field, SPList list)
        {
            var values = new List<string>();
            if (list.Items != null)
            {
                list.Items.Cast<SPListItem>().ToList().ForEach(match => values.Add(match.Title));
            }
            field.Populate(values);
        }

        /// <summary>
        /// Use this method to populate SP Choice field from a list of values
        /// </summary>
        /// <param name="field"></param>
        /// <param name="values"></param>
        public static void Populate(this SPFieldMultiChoice field, List<string> values)
        {
            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(field.SchemaXml);
                {
                    XmlNode node = xmlDoc.SelectSingleNode("//CHOICES");
                    if (node != null && values.Count > 0)
                    {
                        node.RemoveAll(); //Clean old Choices
                        foreach (string value in values)
                        {
                            XmlNode choice = xmlDoc.CreateNode(XmlNodeType.Element, "CHOICE", string.Empty);
                            XmlNode choiceValue = xmlDoc.CreateNode(XmlNodeType.CDATA, string.Empty, string.Empty);
                            choiceValue.Value = value;
                            choice.AppendChild(choiceValue);
                            node.AppendChild(choice);
                        }
                        field.SchemaXml = xmlDoc.InnerXml;
                        field.Update(true);
                    }
                }
            }
            catch (Exception exception)
            {
                exception.Handle();
            }
        }
        #endregion
    }
}